
import axios from "axios";
import querystring from "querystring";
const FormData = require('form-data');
import fs from "fs";
import config from "../config";



const baseUrl = config("api");
let instance = axios.create({
  baseURL: baseUrl,
  timeout: 120000,
})


instance.interceptors.request.use(function (config) {
    return config;
}, function (error) {
	console.log(error)
    return {errorCode:-1,errorMessage:"请求失败"}
});

/**
	errorCode : 0 成功 ，-1 失败，-2 处理中
 */
instance.interceptors.response.use(function (response) {
	return response;
}, function (error) {
	console.log(error , "---err")
	return {
		data:{errorCode:-1,errorMessage:"请求失败"}
	}
});

const ACCESS_TOKEN = "Authorization";
const REFRESH_TOKEN = "X-refresh-token";
const TOKEN_UPDATE = "token-updated";
export default function (app) {

	app.context.post = async function (url,data,config) {
		data = data || {}
		let headers = (config||{}).headers || {};
		
		let result = await instance.post(url,data,{headers:{
			...handleTokens(this),
			...headers,
		}})
		return handleResponese(this,result);
	}

	app.context.put = async function (url,data,config) {
		data = data || {}
		let headers = (config||{}).headers || {};
		
		let result = await instance.put(url,data,{headers:{
			...handleTokens(this),
			...headers,
		}})
		return handleResponese(this,result);
	}

	app.context.get = async function (url,data,config) {
		data = data || {}
		let {headers={},...other} = (config||{});
		let result = await instance.get(url,{
			params:data,
			...other,
			headers:{
				...handleTokens(this),
				...headers,
			}
		})

		return handleResponese(this,result);
	}

	app.context.upload = async function (url,data,config){
		let {headers={},...other} = (config||{});
		const form = new FormData();
		for(let key in data){
			form.append(key, data[key]);
		}
		let result = await instance.post(url, form, { headers: {
			...form.getHeaders() ,
			...handleTokens(this),
			...headers
		}})
		return handleResponese(this,result);
	}

	function handleResponese(ctx,response){
		if(response.headers && response.headers[TOKEN_UPDATE]){
			ctx.access_token = response.headers[TOKEN_UPDATE]
		}
		return response.data || {}
	}
	function handleTokens (ctx) {
		let tokens = {...ctx.http_info};
		if(ctx.access_token){
			tokens[ACCESS_TOKEN] = `Bearer-${ctx.access_token}`
		}
		if(ctx.refresh_token){
			tokens[REFRESH_TOKEN] = `${ctx.refresh_token}`
		}
		return tokens;
	}

}

